<template>
  <div class="banner-top bg-linear"
    id="linear">
    <div class="max-w-11xl px-4 pt-5 pb-5 mx-auto">
      <h1 class="text-center text-3xl sm:text-5xl lg:text-5xl text-gray-1000 leading-normal font-semibold">{{$t('index_banner_title')}}</h1>
      <p class="text-center mt-5 text-base text-gray-1000">
        <common-link path="/#now"
          v-html="$t('index_banner_desc01',{aiNum: aiNum})"></common-link>
        <common-link path="/category"
          v-html="$t('index_banner_desc02',{categoriesNum:categoriesNum})"></common-link>
        {{$t('index_banner_desc03')}}
      </p>

      <sponsored-by class="mt-4 mb-8 text-lg text-gray-1000 font-semibold text-center"></sponsored-by>

      <div class="max-w-2xl mt-5 relative mx-auto">
        <div class="flex items-stretch rounded-lg"
          ref="search">
          <div class="flex-1 relative">
            <input type="text"
              name="toolifySearch"
              v-model="tag"
              class="w-full h-14 text-xl px-5  text-gray-1000 placeholder-gray-1900 outline-none border-white border-transparent focus:outline-none rounded-l-lg"
              @keyup.enter="toPageSearch()"
              @focus="initOptions()"
              :placeholder="$t('index_banner_searchPlacegolder')" />

            <!-- <div class="cursor-pointer absolute top-2 right-3 h-10 px-3 flex items-center leading-none text-lg border border-gray-100 rounded"
              :class="{'text-white border-white bg-purple-1300 hover:opacity-90': useAi,'text-red-500 bg-white border-red-500 hover:border-purple-1300 hover:text-purple-1300 noUse': !useAi}"
              @click="aiUse">
              {{$t('index_banner_byAi')}}
            </div> -->

            <div class="search-result bg-white absolute top-16 left-0 right-0 w-full rounded-lg z-10"
              v-if="visible">

              <virtual-list style="max-height: 400px; overflow-y: auto;"
                v-if="listsOption && listsOption.length >0"
                ref="virtual"
                :data-key="'id'"
                :keeps="15"
                :data-sources="listsOption"
                :data-component="itemComponent"
                :extra-props="{}" />
              <div class="w-2/4 mx-auto pb-4 text-center"
                v-if="searchLoading || (isSearching && listsOption.length === 1)">
                <el-button type="text"
                  class="cursor-default">
                  <img src="@/static/images/loading.png"
                    class="loading"
                    alt=""
                    srcset="">
                </el-button>
              </div>
            </div>
          </div>
          <div class="flex-shrink-0 h-14 px-7 flex items-center bg-purple-1300 hover:opacity-90 rounded-r-lg cursor-pointer"
            @click="toPageSearch()">
            <span class="block w-5 h-5">
              <svg-icon className="block flex-shrink-0 text-white text-xl w-5 h-5"
                iconName='search_white'></svg-icon>
            </span>
            <!-- <span class="hidden sm:block text-xl text-white ml-2">
              {{$t('index_banner_searchBtn')}}
            </span> -->
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import SearchItemNew from '~/components/SearchItemNew.vue'
import VirtualList from 'vue-virtual-scroll-list'
import search from '~/mixins/search'
export default {
  name: 'BannerTop',
  components: { VirtualList },
  mixins: [search],
  props: {
    aiNum: {
      type: Number | String | null,
      default: 0,
    },
    categoriesNum: {
      type: Number | String | null,
      default: 0,
    },
  },
  data() {
    return {
      visible: false,
      tag: null,
      timer: null,
      isSearching: false,

      listsOption: [],
      categoriesList: [],
      toolsList: [],

      itemComponent: SearchItemNew,

      useAi: true,
    }
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
      searchTools: (state) => state.searchTools,
      searchCategory: (state) => state.searchCategory,
      searchLoading: (state) => state.searchLoading,
    }),
  },
  watch: {
    tag: {
      handler() {
        this.initOptions()
      },
      deep: true,
      immediate: true,
    },
    useAi: {
      handler() {
        this.initOptions()
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    /* if (
      this.$route.query.useAi &&
      typeof this.$route.query.useAi === 'string'
    ) {
      if (parseInt(this.$route.query.useAi) === 1) {
        this.useAi = true
      } else if (parseInt(this.$route.query.useAi) === 2) {
        this.useAi = false
      }
    } */
  },
  mounted() {
    document.addEventListener('click', this.clickHandler)
  },
  methods: {
    clickHandler(e) {
      if (this.$refs.search) {
        let self = this.$refs.search.contains(e.target)
        if (!self) {
          this.visible = false
        }
      }
    },
    initOptions() {
      if (this.hasRealVal(this.tag)) {
        this.visible = true
      } else {
        this.visible = false
      }

      if (this.timer) {
        clearTimeout(this.timer)
      }

      this.isSearching = true

      this.listsOption = []

      /* this.timer = setTimeout(() => { */
      if (this.tag) {
        this.listsOption.push({
          type: 'searchFor',
          tag: this.tag,
          id: 'searchFor',
          useAi: this.useAi,
        })
      }

      /* 搜索分类 */
      let categoriesList = []
      let tag
      if (this.hasRealVal(this.tag)) {
        tag = this.tag.toLowerCase()
      }
      if (
        this.searchCategory &&
        this.searchCategory.length > 0 &&
        this.hasRealVal(this.tag)
      ) {
        this.searchCategory.forEach((item, key) => {
          if (typeof this.tag === 'string' && typeof item.n === 'string') {
            if (item.n.toLowerCase() === tag) {
              categoriesList.unshift({
                ...item,
                type: 'category',
                id: `category-${key}`,
                isMatch: true,
                tag: this.tag,
              })
            } else if (item.n.toLowerCase().indexOf(tag) >= 0) {
              categoriesList.push({
                ...item,
                type: 'category',
                id: `category-${key}`,
                tag: this.tag,
              })
            }
          }
        })
      }

      if (categoriesList && categoriesList.length > 0) {
        this.listsOption.push(
          {
            type: 'categories',
            num: categoriesList.length,
            id: 'categories',
            tag: this.tag,
          },
          ...categoriesList
        )
      }
      this.categoriesList = JSON.parse(JSON.stringify(categoriesList))
      /* 搜索分类 end */

      /* 搜索工具 */
      let toolsList = []
      if (
        this.searchTools &&
        this.searchTools.length > 0 &&
        this.hasRealVal(this.tag)
      ) {
        this.searchTools.forEach((item, key) => {
          if (typeof this.tag === 'string' && typeof item.n === 'string') {
            if (item.n.toLowerCase() === tag) {
              toolsList.unshift({
                ...item,
                type: 'tool',
                id: `tool-${key}`,
                isMatch: true,
                tag: this.tag,
              })
            } else if (
              item.n.toLowerCase().indexOf(tag) >= 0
            ) {
              toolsList.push({
                ...item,
                type: 'tool',
                id: `tool-${key}`,
                tag: this.tag,
              })
            }
          }
        })
      }
      if (toolsList && toolsList.length > 0) {
        this.listsOption.push(
          {
            type: 'tools',
            num: toolsList.length,
            id: 'tools',
            tag: this.tag,
          },
          ...toolsList
        )
      }
      this.toolsList = JSON.parse(JSON.stringify(toolsList))
      /* 搜索工具 end */

      /* total */
      if (
        (categoriesList && categoriesList.length > 0) ||
        (toolsList && toolsList.length > 0)
      ) {
        this.listsOption.push({
          type: 'total',
          num: categoriesList.length + toolsList.length,
          id: 'total',
        })
      }
      /* total end */

      this.isSearching = false
      /* }, 30) */
    },
    toPageSearch() {
      this.visible = false
      if (this.hasRealVal(this.tag)) {
        if (
          this.categoriesList &&
          this.categoriesList.length > 0 &&
          this.categoriesList[0].isMatch
        ) {
          this.searchStatistics(
            `https://www.toolify.ai${
              this.locale === 'en' ? '' : `/${this.locale}`
            }/category/${this.categoriesList[0].h}`,
            this.tag,
            0
          )
          /* this.$router.push({
            name:
              this.locale === 'en' ? 'category-handle' : 'lang-category-handle',
            params: {
              lang: this.locale,
              handle: this.categoriesList[0].h,
            },
          }) */

          const routeData = this.$router.resolve({
            name:
              this.locale === 'en' ? 'category-handle' : 'lang-category-handle',
            params: {
              lang: this.locale,
              handle: this.categoriesList[0].h,
            },
          })
          window.open(routeData.href, '_blank')
        } else if (
          this.toolsList &&
          this.toolsList.length > 0 &&
          this.toolsList[0].isMatch
        ) {
          this.searchStatistics(
            `https://www.toolify.ai${
              this.locale === 'en' ? '' : `/${this.locale}`
            }/tool/${this.toolsList[0].h}`,
            this.tag,
            0
          )
          /* this.$router.push({
            name: this.locale === 'en' ? 'tool-handle' : 'lang-tool-handle',
            params: {
              lang: this.locale,
              handle: this.toolsList[0].h,
            },
          }) */
          const routeData = this.$router.resolve({
            name: this.locale === 'en' ? 'tool-handle' : 'lang-tool-handle',
            params: {
              lang: this.locale,
              handle: this.toolsList[0].h,
            },
          })
          window.open(routeData.href, '_blank')
        } else {
          /* this.$router.push({
            name: this.locale === 'en' ? 'search-handle' : 'lang-search-handle',
            params: {
              lang: this.locale,
              handle: encodeURIComponent(this.tag),
            },
          }) */

          const routeData = this.$router.resolve({
            name: this.locale === 'en' ? 'search-handle' : 'lang-search-handle',
            params: {
              lang: this.locale,
              handle: encodeURIComponent(this.tag),
            },
            query: {
              r: this.$route.name.replace('lang-', ''),
              /* useAi: this.useAi ? 1 : 2, */
            },
          })
          window.open(routeData.href, '_blank')
        }
      }
    },
    toNow() {
      const dom = document.querySelector('#index_now-0')
      if (dom) {
        this.isScrolling = true
        const top = dom.offsetTop

        const targetScrollPosition = Math.max(top - 100, 0)

        window.scrollTo({
          top: targetScrollPosition,
          behavior: 'smooth',
        })
        this.$nextTick(() => {
          this.isScrolling = false
        })
      }
    },
    aiUse() {
      this.useAi = !this.useAi
    },
  },
  beforeDestroy() {
    if (this.timer) {
      clearTimeout(this.timer)
    }
    document.removeEventListener('click', this.clickHandler)
  },
}
</script>
<style lang='scss' scoped>
.banner-top {
  .search-result {
    box-shadow: 0px 4px 23px 0px rgba(0, 0, 0, 0.12);
    max-height: 480px;
  }
  input::placeholder {
    font-size: 16px;
  }
  .noUse {
    position: relative;
    &:not(:hover) {
      &::before {
        position: absolute;
        content: ' ';
        height: 100%;
        width: 100%;
        background: linear-gradient(
          to top right,
          rgba(0, 0, 0, 0),
          rgba(0, 0, 0, 0) 48%,
          #ef4444,
          rgba(0, 0, 0, 0) 51%,
          rgba(0, 0, 0, 0)
        );
        left: 0;
        top: 0;
      }
    }
  }
}
</style>